package com.wqm.step.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.wqm.step.dao.ManyToManyDao;
import com.wqm.step.pojo.Student;
import com.wqm.step.pojo.Teacher;

@Repository
public class ManyToManyDaoImpl extends HibernateDaoSupport implements ManyToManyDao {

	@Autowired
	public void setSuperSessionFactory(SessionFactory factory) {
		super.setSessionFactory(factory);
	}

	/**
	 * 多对多，级联保存
	 * 多对多最好两边都配置级联,详细看Customer类中级联讲解
	 */
	public void saveManyToMany(Teacher t1, Teacher t2, Student s1, Student s2) {
		Session session = this.getSessionFactory().getCurrentSession();
		// 3.学生关联老师
		s1.getTeachers().add(t1);
		s1.getTeachers().add(t2);

		s2.getTeachers().add(t1);
		s2.getTeachers().add(t2);

		// 4.保存学生
		session.save(s1);
		session.save(s2);
	}

	/**
	 * 	注意！！！！ ： 这个方法最好不要用， 会删除所有数据的 *—*，最好级联就设置成save-update
	 * 多对多， 级联删除 (前提是建立了双向的级联 All)
	 * 多对多最好两边都配置级联,详细看Customer类中级联讲解
	 */
	public void deleteData(Integer id) {
		Session session = this.getSessionFactory().getCurrentSession();
		// 先查询数据，再删除数据
		Student student = session.get(Student.class, id);
		session.delete(student);
	}

}
